package com.android.tvservicer;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

import java.util.List;

/**
 * Created by mr.kong on 2017/9/28.
 */

public class NetworkChangeBroadcast extends BroadcastReceiver {
    private ConnectivityManager mConnectivityManager;
    private NetworkInfo netInfo;


    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            netInfo = mConnectivityManager.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isAvailable()) {

                /////////////网络连接
                String name = netInfo.getTypeName();
                if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    /////WiFi网络
                    Toast.makeText(context, "WIFI网络", Toast.LENGTH_LONG).show();
                    updateService(context);

                } else if (netInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                    /////有线网络
                    Toast.makeText(context, "有限网络", Toast.LENGTH_LONG).show();
                    updateService(context);
                }
            } else {
                ////////网络断开
                Toast.makeText(context, "无网络", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void updateService(Context context) {
        if (!isServiceWork(context, "RegisterBoardDeviceServer")) {
            context.stopService(new Intent(context, RegisterBoardDeviceServer.class));
            context.startService(new Intent(context, RegisterBoardDeviceServer.class));
        }
    }


    public boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(100);
        if (myList.size() <= 0) {
            return false;
        }
        int size = myList.size();
        for (int i = 0; i < size; i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }
}

